package com.imooc.service.impl;

import com.imooc.enums.Sex;
import com.imooc.mapper.UsersMapper;
import com.imooc.pojo.Users;
import com.imooc.pojo.bo.UserBo;
import com.imooc.service.UserService;
import com.imooc.utils.DateUtil;
import com.imooc.utils.MD5Utils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UsersMapper usersMapper;

    //我们配置componentScan注解让这个sid类被spring扫描到了
    @Autowired
    private Sid sid;

    //这是默认头像33娘
    public static final String USER_FACE = "https://i0.hdslb.com/bfs/face/6e7ee177b5cc681b9609c07f8d5eb574b52d409c.jpg@150w_150h.jpg";

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUsernameIsExist(String username) {
        Example userExample = new Example(Users.class);
        Example.Criteria userCriteria = userExample.createCriteria();
        //条件拼接,将实体内部的username字段和传入的username参数进行相等比较
        userCriteria.andEqualTo("username", username);
        Users result = usersMapper.selectOneByExample(userExample);
        return result != null;
    }

    //这里我们是用于创建业务,所以必须有个事务用于回滚
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users createUser(UserBo userBO) {
        String userId = sid.nextShort();
        Users users = new Users();
        users.setId(userId);
        users.setUsername(userBO.getUsername());
        try {
            //我们要把密码加密,防止数据库被黑客攻击的时候密码泄露造成用户信息泄露
            users.setPassword(MD5Utils.getMD5Str(userBO.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //默认用户昵称就是用户名
        users.setNickname(userBO.getUsername());
        //设置默认头像
        users.setFace(USER_FACE);
        //设置默认生日
        users.setBirthday(DateUtil.stringToDate("1900-01-01"));
        //不要写死数据,用枚举实现数据透明化,默认为保密"2"
        users.setSex(Sex.secret.type);
        users.setCreatedTime(new Date());
        users.setUpdatedTime(new Date());
        usersMapper.insert(users);
        return users;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserForLogin(String username, String password) {

        Example userExample = new Example(Users.class);
        Example.Criteria userCriteria = userExample.createCriteria();
        //条件拼接,将实体内部的username字段和传入的username参数进行相等比较
        userCriteria.andEqualTo("username", username);
        userCriteria.andEqualTo("password", password);
        Users result = usersMapper.selectOneByExample(userExample);
        return result;
    }
}